<template>
  <div class="login_box">
    <div class="l_comtent">
      <h2>叩丁狼电商管理系统</h2>
      <section>
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >
          <el-form-item prop="username">
            <el-input
              type="text"
              v-model="ruleForm.username"
              autocomplete="off"
              placeholder="用户名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="pwd">
            <el-input
              type="password"
              v-model="ruleForm.pwd"
              autocomplete="off"
              placeholder="密码"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%" @click="loginFn"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </section>
    </div>
  </div>
</template>
 
<script>
import { loginApi } from "../../request/api";
export default {
  data() {
    return {
      ruleForm: {
        username: "",
        pwd: "",
      },
      rules: {
        username: [
          { required: true, message: "账号不能为空", trigger: "blur" },
          { validator: this.userNameVali, trigger: "blur" },
        ],
        pwd: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { validator: this.pwdVali, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //  校验账号
    userNameVali(rule, value, callback) {
      if (value && value.length > 1 && value.length < 20) {
        callback();
      } else {
        callback("账号长度为1~20个字符");
      }
    },
    // 校验密码
    pwdVali(rule, value, callback) {
      if (!value) {
        callback("账号长度为1~18个字符");
      } else {
        callback();
      }
    },
    //   点击登录
    loginFn() {
      // 触发(调用)Form的校验方法
      this.$refs["ruleForm"].validate().then(() => {
        loginApi({
          password: this.ruleForm.pwd,
          username: this.ruleForm.username,
        }).then((res) => {
          console.log(res);
          if (res.errno === 0) {
            localStorage.setItem("token", res.data.token);
            this.$store.commit("SAVEMENU", res.data.menu);
            this.$router
              .push("/homepage")
              .then(() => {})
              .catch(() => {});
          }
        });
      });
    },
  },
};
</script>
 
<style lang = "less" scoped>
.login_box {
  width: 100%;
  height: 100%;
  background-color: #324057;
  position: relative;
  top: 0;
  left: 0;
  .l_comtent {
    width: 330px;
    height: 210px;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    h2 {
      text-align: center;
      color: #fff;
      margin-bottom: 10px;
    }
  }
}
</style>